<template>
  <div class="app-container">
    <div class="header-section">
      <div class="filter-section">
        <div class="filter-wrapper">
          开始时间：
          <el-date-picker
            v-model="filterStartDate"
            type="date"
            placeholder="选择开始日期"
            value-format="YYYY-MM-DD"
            class="date-picker"
          />
          结束时间：
          <el-date-picker
            v-model="filterEndDate"
            type="date"
            placeholder="选择结束日期"
            value-format="YYYY-MM-DD"
            class="date-picker"
          />
          家庭id：
          <el-input
            v-model="filterHouseId"
            placeholder="房屋ID"
            clearable
            class="input-field"
          />
          
          <el-button 
            type="primary" 
            @click="handleSearch"
            class="search-btn"
          >
            查询
          </el-button>
        </div>
      </div>
      
      <div class="add-asset-btn">
        <el-button 
          type="primary" 
          icon="Plus" 
          @click="showAddAssetModal = true"
          class="add-btn"
        >
          新增资产
        </el-button>
      </div>
    </div>

    <div class="table-section">
      <el-table 
        :data="pagedAssets" 
        border 
        stripe 
        v-loading="loading"
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa' }"
        @row-click="handleRowClick"
      >
        <el-table-column
          v-for="col in columns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :align="col.align"
          :min-width="col.minWidth"
          sortable
        >
          <template #default="scope">
            <span v-if="col.prop === 'amount'">
              {{ Number(scope.row[col.prop]).toLocaleString() }}
            </span>
            <span v-else-if="col.prop === 'updateTime'">
              {{ formatDateTime(scope.row[col.prop]) }}
            </span>
            <span v-else>
              {{ scope.row[col.prop] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column 
          label="操作" 
          width="120" 
          align="center"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              @click="confirmDelete(row)"
              circle
              style="margin-right: 10px;"
            />
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="showUpdateAssetModalFn(row)"
              circle
            />
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          background
          :layout="'total, prev, pager, next, sizes, jumper'"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增资产对话框 -->
    <el-dialog 
      v-model="showAddAssetModal" 
      title="新增资产" 
      width="500px"
      center
      class="add-asset-dialog"
    >
      <el-form 
        :model="form" 
        label-width="80px" 
        label-position="left"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="资产标题" prop="title">
          <el-input 
            v-model="form.title" 
            placeholder="请输入资产名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="资产类型" prop="assetName">
          <el-select
            v-model="form.assetName"
            placeholder="选择资产类型"
            class="asset-select"
          >
            <el-option label="家庭资产" value="家庭资产" />
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number
            v-model="form.amount"
            :min="0"
            :precision="2"
            controls-position="right"
            class="amount-input"
          />
        </el-form-item>
        <el-form-item label="房屋ID">
          <el-input-number
            v-model="form.houseId"
            :min="0"
            controls-position="right"
            class="house-id-input"
          />
        </el-form-item>
        <el-form-item label="备注信息">
          <el-input
            v-model="form.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="100"
            show-word-limit
            class="remarks-textarea"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAddAssetModal = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSubmit"
            :loading="submitting"
          >
            确认提交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 更新资产对话框 -->
    <el-dialog 
      v-model="isUpdateAssetModalVisible" 
      title="更新资产" 
      width="500px"
      center
      class="update-asset-dialog"
    >
      <el-form 
        :model="updateForm" 
        label-width="80px" 
        label-position="left"
        :rules="rules"
        ref="updateFormRef"
      >
        <el-form-item label="资产标题" prop="title">
          <el-input 
            v-model="updateForm.title" 
            placeholder="请输入资产名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="资产类型" prop="assetName">
          <el-select
            v-model="updateForm.assetName"
            placeholder="选择资产类型"
            class="asset-select"
          >
            <el-option label="家庭资产" value="家庭资产" />
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number
            v-model="updateForm.amount"
            :min="0"
            :precision="2"
            controls-position="right"
            class="amount-input"
          />
        </el-form-item>
        <el-form-item label="备注信息">
          <el-input
            v-model="updateForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="100"
            show-word-limit
            class="remarks-textarea"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isUpdateAssetModalVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleUpdate"
            :loading="submitting"
          >
            确认更新
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { assetsList, assetsAdd, assetsDelete, assetsUpdate } from '@/api/assets'
import dayjs from 'dayjs'

// 表格列配置
const columns = [
  { prop: 'title', label: '资产标题', minWidth: '120px' },
  { prop: 'assetName', label: '资产类型', minWidth: '120px' },
  { 
    prop: 'amount', 
    label: '金额（元）', 
    align: 'right'
  },
  { prop: 'houseId', label: '房屋ID', align: 'center' },
  { prop: 'remarks', label: '备注信息', minWidth: '180px' },
  { 
    prop: 'updateTime', 
    label: '最后更新时间', 
    minWidth: '160px'
  }
]

// 响应式数据
const currentPage = ref(1)
const pageSize = ref(10)
const assets = ref([])
const total = ref(0)
const loading = ref(false)
const filterStartDate = ref('')
const filterEndDate = ref('')
const filterHouseId = ref('')
const showAddAssetModal = ref(false)
const isUpdateAssetModalVisible = ref(false)
const submitting = ref(false)
const form = ref({
  title: '',
  amount: null,
  assetName: '',
  remarks: '',
  houseId: null
})
const updateForm = ref({
  id: null,
  title: '',
  amount: null,
  assetName: '',
  remarks: ''
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入资产标题', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
  assetName: [{ required: true, message: '请选择资产类型', trigger: 'change' }]
}

// 获取资产数据
const fetchAssets = async () => {
  try {
    loading.value = true
    const params = {
      createTime: filterStartDate.value 
        ? dayjs(filterStartDate.value).format('YYYY-MM-DD HH:mm:ss') 
        : null,
      endTime: filterEndDate.value 
        ? dayjs(filterEndDate.value).format('YYYY-MM-DD HH:mm:ss') 
        : null,
      houseId: filterHouseId.value || null
    }

    const res = await assetsList(params)
    console.log('API Response:', res) // 打印 API 返回数据，用于调试
    if (res.data.code === 200) {
      assets.value = res.data.data || []
      total.value = assets.value.length // 根据前端数据计算总数据量
    } else {
      ElMessage.error(res.data.msg || '获取数据失败')
    }
  } catch (error) {
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  return dayjs(dateStr).format('YYYY-MM-DD HH:mm:ss')
}

// 分页事件处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

// 计算分页后的数据
const pagedAssets = computed(() => {
  if (!assets.value || assets.value.length === 0) return []
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return assets.value.slice(startIndex, endIndex)
})

// 删除确认
const confirmDelete = async (row) => {
  try {
    await ElMessageBox.confirm('此操作将永久删除该资产，是否继续？', '警告', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消操作',
      type: 'warning',
      center: true,
      confirmButtonClass: 'el-button--danger'
    })

    // 调用删除接口
    const params = {
      id: row.id
    }
    await assetsDelete(params)
    
    await fetchAssets()
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.info('取消删除')
  }
}

// 显示更新资产对话框
const showUpdateAssetModalFn = (row) => {
  updateForm.value = {
    id: row.id,
    title: row.title,
    amount: row.amount,
    assetName: row.assetName,
    remarks: row.remarks || ''
  }
  isUpdateAssetModalVisible.value = true
}

// 更新资产
const handleUpdate = async () => {
  submitting.value = true
  try {
    const params = {
      id: updateForm.value.id,
      title: updateForm.value.title,
      assetName: updateForm.value.assetName,
      amount: updateForm.value.amount,
      remark: updateForm.value.remarks
    }

    const res = await assetsUpdate(params)
    if (res.data.code === 200) {
      ElMessage.success('资产更新成功')
      isUpdateAssetModalVisible.value = false
      await fetchAssets()
    } else {
      ElMessage.error(res.data.msg || '资产更新失败')
    }
  } catch (error) {
    ElMessage.error('资产更新失败')
  } finally {
    submitting.value = false
  }
}

// 提交新增资产
const handleSubmit = async () => {
  submitting.value = true
  try {
    const params = {
      title: form.value.title,
      assetName: form.value.assetName,
      amount: form.value.amount,
      houseId: form.value.houseId,
      remark: form.value.remarks
    }

    const res = await assetsAdd(params)
    if (res.data.code === 200) {
      ElMessage.success('资产添加成功')
      showAddAssetModal.value = false
      form.value = {
        title: '',
        amount: null,
        assetName: '',
        remarks: '',
        houseId: null
      }
      await fetchAssets()
    } else {
      ElMessage.error(res.data.msg || '资产添加失败')
    }
  } catch (error) {
    ElMessage.error('资产添加失败')
  } finally {
    submitting.value = false
  }
}

// 搜索逻辑
const handleSearch = () => {
  currentPage.value = 1
  fetchAssets()
}

// 初始化加载
onMounted(() => {
  fetchAssets()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 25px;
  background: #f7f9fc;
  min-height: calc(100vh - 60px);
}

.header-section {
  display: flex;
  justify-content: space-between;
  margin-bottom: 25px;
  background: white;
  border-radius: 8px;
  padding: 15px 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  
  .filter-section {
    flex: 1;
    
    .filter-wrapper {
      display: flex;
      gap: 10px;
      align-items: center;
      
      .date-picker,
      .input-field {
        flex: 1;
        min-width: 120px;
        max-width: 180px;
      }
      
      .search-btn {
        margin-left: 10px;
        padding: 0 18px;
        height: 36px;
        font-size: 14px;
      }
    }
  }
  
  .add-asset-btn {
    margin-left: 15px;
    
    .add-btn {
      font-size: 14px;
      padding: 9px 18px;
      height: 36px;
      display: flex;
      align-items: center;
      gap: 6px;
    }
  }
}

.table-section {
  padding: 25px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  
  :deep(.el-table) {
    .el-table__row {
      height: 56px;
      
      &:hover {
        background-color: #f0f7ff;
      }
    }
    
    th {
      background-color: #f5f7fa;
      font-weight: 500;
      color: #333;
    }
    
    .el-button {
      padding: 6px;
      font-size: 14px;
    }
  }
  
  .pagination-wrapper {
    margin-top: 25px;
    display: flex;
    justify-content: flex-end;
    
    :deep(.el-pagination) {
      .btn-prev,
      .btn-next,
      .el-pager li {
        width: 32px;
        height: 32px;
        line-height: 32px;
        font-size: 13px;
      }
      
      .el-pager li.active {
        background-color: #409eff;
        color: white;
      }
      
      .el-input {
        width: 90px;
      }
    }
  }
}

.add-asset-dialog,
.update-asset-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    
    .el-dialog__header {
      background: #f5f7fa;
      padding: 18px 25px;
      border-radius: 12px 12px 0 0;
    }
    
    .el-dialog__body {
      padding: 25px;
    }
    
    .el-form-item {
      margin-bottom: 20px;
      
      .el-form-item__label {
        font-weight: 500;
      }
      
      .el-input,
      .el-select,
      .el-input-number,
      .el-textarea {
        width: 100%;
      }
    }
    
    .remarks-textarea {
      textarea {
        resize: none;
      }
    }
    
    .dialog-footer {
      display: flex;
      justify-content: flex-end;
      gap: 15px;
      margin-top: 25px;
    }
  }
}
</style>